import mysql.connector
from mysql.connector import Error


def test_mysql_connection():
    try:
        # 创建连接
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='123456',  # 替换为你的密码
            database='djangodb'  # 使用你创建的数据库
        )

        if connection.is_connected():
            print("✅ 成功连接到 MySQL 数据库")

            # 获取数据库信息
            db_info = connection.server_info
            print(f"MySQL 服务器版本: {db_info}")

            # 执行简单查询
            cursor = connection.cursor()
            cursor.execute("SELECT DATABASE()")
            db_name = cursor.fetchone()[0]
            print(f"当前数据库: {db_name}")

            # 创建测试表并插入数据
            cursor.execute(
                "CREATE TABLE IF NOT EXISTS test_table (id INT AUTO_INCREMENT PRIMARY KEY, message VARCHAR(255))")
            cursor.execute("INSERT INTO test_table (message) VALUES ('测试连接成功!')")
            connection.commit()

            # 查询数据
            cursor.execute("SELECT * FROM test_table")
            records = cursor.fetchall()
            print("测试表内容:")
            for row in records:
                print(f"ID: {row[0]}, Message: {row[1]}")

    except Error as e:
        print(f"❌ 连接失败: {e}")

    finally:
        # 关闭连接
        if connection and connection.is_connected():
            cursor.close()
            connection.close()
            print("⛔ MySQL 连接已关闭")


# 执行测试
if __name__ == "__main__":
    test_mysql_connection()